package com.example.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Service
public class AsyncService {
    
    private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
    
    private final Executor asyncExecutor;
    private final Executor ioExecutor;

    public AsyncService(
            @Qualifier("asyncExecutor") Executor asyncExecutor,
            @Qualifier("ioExecutor") Executor ioExecutor) {
        this.asyncExecutor = asyncExecutor;
        this.ioExecutor = ioExecutor;
    }
    
    /**
     * 简单异步任务示例
     */
    public CompletableFuture<String> executeAsyncTask(String taskName) {
        log.info("开始执行异步任务: {}", taskName);
        
        return CompletableFuture.supplyAsync(() -> {
            log.info("异步任务执行中: {}", taskName);
            try {
                // 模拟耗时操作
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("任务执行被中断: {}", e.getMessage());
            }
            return "任务 " + taskName + " 已完成";
        }, asyncExecutor);
    }
    
    /**
     * 使用IO线程池的异步任务
     */
    public CompletableFuture<String> executeIoTask(String taskName) {
        log.info("开始执行IO异步任务: {}", taskName);
        
        return CompletableFuture.supplyAsync(() -> {
            log.info("IO异步任务执行中: {}", taskName);
            try {
                // 模拟IO操作
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("IO任务执行被中断: {}", e.getMessage());
            }
            return "IO任务 " + taskName + " 已完成";
        }, ioExecutor);
    }
    
    /**
     * 获取异步执行器
     */
    public Executor getAsyncExecutor() {
        return asyncExecutor;
    }
    
    /**
     * 获取IO执行器
     */
    public Executor getIoExecutor() {
        return ioExecutor;
    }
}